<template>
	<view class="app">
		<authorize @onLoadFun="onLoadFun"></authorize>
		<view class="app-container">
			<view class="publish-wrap">
				<view class="card">
					<view class="cu-form-group">
						<view class="title-wrap">需求类型</view>
						<picker @change="demandPickerChange" :value="currentDemandIndex" :range="demands" range-key="demand_type_name">
							<view class="picker">
								<text v-if="currentDemandIndex > -1" class="text-black">{{ demands[currentDemandIndex].demand_type_name}}</text>
								<text v-else class="input-placeholder">请输入需求类型</text>
							</view>
						</picker>
					</view>
				</view>
				<view class="card">
					<view class="cu-form-group"  @tap="selectAddress">
						<view class="title-wrap" style="width: 200rpx;">收货地址</view>
						<text class="text-gray fr text-cut text-right">
							<text v-if="address.shipping_address_id" class="text-black">{{address.address}}</text>
							<text v-else>请选择收货地址</text>
							<text class="cuIcon-right"></text>
						</text>
					</view>
					<!-- 收件人名称 -->
					<view class="cu-form-group" v-show="demands[currentDemandIndex].demand_type_id === 3">
						<view class="title-wrap">收件人名称</view>
						<input placeholder="请输入收件人名称" class="text-black" name="input" v-model="address.name"></input>
					</view>
					<!-- 打印订单 -->
					<view class="cu-form-group"  @tap="showModal" v-show="demands[currentDemandIndex].demand_type_id === 1">
						<view class="title-wrap">选择打印订单</view>
						<view class="text-gray fr text-cut text-right">
							<text v-if="selectedOrder.print_order_id" class="text-black">CODE({{selectedOrder.code}})</text>
							<text v-else>请选择打印订单</text>
							<text class="cuIcon-right" data-target="bottomModal"></text>
						</view>
					</view>
					<!-- 快递公司 -->
					<view class="cu-form-group"  v-show="demands[currentDemandIndex].demand_type_id === 3">
						<view class="title-wrap">快递公司</view>
						<picker @change="companyPickerChange" :value="currentCompanyIndex" :range="expressCompanys" range-key="courier_services_company_name">
							<view class="picker">
								<text v-if="currentCompanyIndex" class="text-black">{{ expressCompanys[currentCompanyIndex].courier_services_company_name}}</text>
								<text v-else class="input-placeholder">请选择快递公司</text>
							</view>
						</picker>
					</view>
					<!-- 派送时间 -->
					<view class="cu-form-group"  v-show="demands[currentDemandIndex].demand_type_id === 3">
						<view class="title-wrap">派送时间</view>
						<picker @change="periodsPickerChange" :value="currentPeriodsIndex" :range="periods">
							<view class="picker">
								<text v-if="currentPeriodsIndex" class="text-black">{{ periods[currentPeriodsIndex]}}</text>
								<text v-else class="input-placeholder">请选择派送时间</text>
							</view>
						</picker>
					</view>
					<!-- 支付方式 -->
					<view class="cu-form-group">
						<view class="title-wrap">支付方式</view>
						<picker @change="pickerPaymentMethodsChange" :value="paymentMethodIndex" :range="paymentMethods" range-key="name">
							<view class="picker">
								<text class="text-black">{{ paymentMethods[paymentMethodIndex].name }}</text>
							</view>
						</picker>
					</view>
				</view>
				<view class="card" v-if="demands[currentDemandIndex].demand_type_id === 3">
					<textarea v-if="!bottomModal && !payFlag && !couponsListVisibility" v-model="express_message" placeholder="复制快递短信到此处" placeholder-class="text-gray text-normal"></textarea>
					<text v-else>{{express_message}}</text>
				</view>
				<view class="card">
					<textarea v-if="!bottomModal && !payFlag && !couponsListVisibility" v-model="describe" :maxlength="80" placeholder="输入描述" placeholder-class="text-gray text-normal"></textarea>
					<text v-else>{{describe}}</text>
				</view>
				<view class="card">
					<view class="cu-list menu">
						<view class="cu-form-group"  @tap="filterCouponsEvent">
							<view class="title-wrap" style="width: 200rpx;">使用优惠券</view>
							<text class="text-gray fr text-cut text-right">
								<text v-if="couponsIndex > -1" class="text-black">{{filterCoupons[couponsIndex].discount_coupon_name}}</text>
								<text v-else>请选择优惠券</text>
								<text class="cuIcon-right"></text>
							</text>
						</view>
						<view class="cu-item cu-form-group">
							<view class="content title-wrap">
								合计费用
							</view>
							<view class="action text-gray">￥{{ couponsIndex > -1 ? filterCoupons[couponsIndex].type ? totalPrice * couponPrice > 0 ? (totalPrice * couponPrice).toFixed(2) : 0 : totalPrice - couponPrice > 0 ? (totalPrice - couponPrice).toFixed(2) : 0 : totalPrice}}</view>
						</view>
					</view>
				</view>
				<button class="form-btn cu-btn block bg-primary lg" :class="{ 'isIphoneX-class': isIphoneX }" @tap="publishEvent">提交需求</button>
			</view>
		</view>
		<!-- 底部model 用于选择打印订单 -->
		<view class="cu-modal bottom-modal" :class="{'show': bottomModal}">
			<view class="cu-dialog print-dialog">
				<view class="cu-bar bg-white">
					<!-- <view class="action text-green" @tap="confirmOrder">确定</view> -->
					<view class="action text-blue fr" @tap="hideModal">关闭窗口</view>
				</view>
				<view class="padding-xl list-wrap">
					<view class="cu-list menu" :class="{ 'isIphoneX-class': isIphoneX }">
						<view class="cu-item" v-for="(item, index) in list" :key="index" @tap="confirmOrder(item)">
							<view class="content padding-tb-sm">
								<view class="text-cut">{{item.file_name || '暂时无法获取到文件名'}}</view>
								<view class="text-left text-gray text-sm">{{item.create_time}}</view>
							</view>
							<view class="action text-gray">
								<text class="cuIcon-infofill"></text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<PaymentModal ref="PaymentModal" :title="paymentModalTitle" v-model="payFlag" @confirm="confirmPassword"></PaymentModal>
		<CouponsList v-model="couponsListVisibility" :coupon="filterCoupons" :openType="1" @changCoupons="changCoupons"></CouponsList>
	</view>
</template>

<script>
	import {mapGetters} from 'vuex'
	import Authorize from '@/components/authorize/authorize';
	import { getUserInfo, changePaymentCode } from '@/api/user';
	import {getDemandTypeCourierServicesCompany, postDemand } from '@/api/community.js'
	import { getCloudPrintHistoryOrderList } from '@/api/order.js';
	import PaymentModal from '@/components/payment-modal/password.vue';
	import { CouponsList } from '@/components/coupons-list/coupons-list.vue';
	import { getWechatUserDiscountCouponInfoList } from '@/api/common.js';
	import { paymentInterface } from '../api/pay';
    export default {
        name: "publish",
		data() {
			return {
				//派送时间段
				periods: ['10:00~13:00','14:00~18:00','19:00~22:00'],
				//需求列表
				demands: [],
				//打印订单列表
				list: [],
				bottomModal: false,
				//快递信息
				express_message: '',
				//需求描述
				describe: '',
				address: {},
				//支付方式
				paymentMethods: [
					{
						name: '微信支付',
						value: 2
					},{
						name: '余额支付',
						value: 1
					}
				],
				//选择的打印订单
				selectedOrder: {},
				//生成订单号的返回值
				order_result: {},
				//选择的支付方式下标
				paymentMethodIndex: 1,
				//current派送时间
				currentPeriodsIndex: null,
				//current需求类型
				currentDemandIndex: -1,
				//current快递公司
				currentCompanyIndex: null,
				expressCompanys: [],
				//用户信息
				userInfo: {},
				//控制余额支付显示隐藏
				payFlag: false,
				//余额支付组件标题
				paymentModalTitle: '',
				//优惠券列表
				coupons: [],
				//过滤不符合条件得优惠券列表
				filterCoupons: [],
				//选择的优惠券下标
				couponsIndex: -1,
				//优惠券组件 dialog 框
				couponsListVisibility: false,
			}
		},
		components: {
			Authorize,
			PaymentModal,
			CouponsList
		},
		computed: {
			...mapGetters(['isIphoneX']),
			totalPrice() {
				return this.currentDemandIndex > -1 ? this.demands[this.currentDemandIndex].price : 0
			},
			couponPrice() {
				const coupon = this.filterCoupons[this.couponsIndex]
				//判断使用使用优惠券
				//判断优惠券类型，0为立减，1为折扣
				return this.couponsIndex > -1 ? coupon.type ? Number(coupon.discount) * 0.1 : Number(coupon.subtract_price) : 0
			},
		},
		onLoad() {
			this.getDemandTypeCourierServicesCompanyEvent()
			this.getCloudPrintHistoryOrderListEvent()
			this.getCouponInfoList()
		},
		onShow() {
			uni.getStorage({
				key: 'selectAddress',
				success:(e) => {
					this.address = e.data
				}
			});
		},
		methods: {
			onLoadFun() {
				this.getUserInfoEvent();
			},
			getUserInfoEvent() {
				return new Promise((resolve, reject) => {
					getUserInfo().then(res => {
						this.userInfo = res.result;
						resolve(res.result);
					});
				});
			},
			/**
			 * 查询需求类型选择框数据和快递公司选择框数据
			 */
			getDemandTypeCourierServicesCompanyEvent() {
				getDemandTypeCourierServicesCompany().then(res => {
					this.demands = res.result.demand_type
					this.expressCompanys = res.result.courier_services_company
				})
			},
			/**
			 * 查询用户优惠券信息列表
			 */
			getCouponInfoList() {
				getWechatUserDiscountCouponInfoList({
					type: 2
				}).then(res => {
					this.coupons = res.result.showing
				})
			},
			/**
			 * 过滤当前价格可使用的优惠券
			 */
			filterCouponsEvent() {
				this.couponsListVisibility =  true
				this.filterCoupons = this.coupons.filter(v => {
					return Number(this.totalPrice) >= Number(v.full_price)
				})
				console.log(this.filterCoupons)
			},
			/**
			 * 选择优惠券
			 * @param e 优惠券
			 */
			changCoupons(item, index) {
				//把全部可用优惠券变为未使用状态
				this.filterCoupons.forEach( v => {
					v.is_use = false
				})
				//判断选择项是否被使用状态 取反
				if (item.is_use) {
					item.is_use = false
					index = -1
				}else {
					item.is_use = true
				}
				this.coupons.forEach(v => {
					if(v.discount_coupon_id === item.discount_coupon_id) {
						v.is_use = item.is_use
					}
				})
				this.couponsIndex = index
			},
			/**
			 * 检索已付款未打印的订单
			 */
			getCloudPrintHistoryOrderListEvent() {
				getCloudPrintHistoryOrderList({
					status: 2,
					pageSize: '',
					currentPage: ''
				}).then(res => {
					 this.list = res.result.showing
				})
			},
			/**
			 * 时间段选择
			 * @param {Object} e
			 */
			periodsPickerChange(e) {
				this.currentPeriodsIndex = e.detail.value;
			},
			/**
			 * 快递公司选择
			 * @param {Object} e
			 */
			companyPickerChange(e) {
				this.currentCompanyIndex = e.detail.value;
			},
			/**
			 * 需求类型选择
			 * @param {Object} e
			 */
			demandPickerChange(e) {
				this.currentDemandIndex = e.detail.value;
				this.coupons.forEach( v => {
					v['is_use'] = false
				})
				this.couponsIndex = -1
			},
			showModal() {
				this.bottomModal = true
			},
			hideModal() {
				this.bottomModal = false
			},
			/**
			 * 确认选择订单
			 * @param {Object} item
			 */
			confirmOrder(item) {
				this.selectedOrder = item
				this.hideModal()
			},
			/**
			 * 选择收货人信息
			 */
			selectAddress() {
				uni.navigateTo({
					url:'/user-pages/address/address?type=select'
				})
			},
			/**
			 * 选择支付方式
			 * @param e 微信/余额
			 */
			pickerPaymentMethodsChange(e) {
				// 微信支付封印
				if (e.detail.value === '0') {
					uni.showToast({
						icon: 'none',
						title: '微信支付功能正在建设中~(๑•̀ㅂ•́)و✧'
					});
					return;
				}
				this.paymentMethodIndex = e.detail.value;
			},
			/**
			 * 发布
			 */
			publishEvent() {
				//没有生成订单号时
				if (!this.order_id) {
					//第一步：生成订单号
					this.postDemand().then((order_result) => {
						this.payType(order_result);
					});
				} else {
					this.payType(this.order_result);
					this.isDisabled = false;
				}


				// uni.showToast({
				// 	title: '已成功提交需求，大约需要人工审核5~10分钟，请耐心等待',
				// 	success: () => {
				// 		uni.navigateBack();
				// 	}
				// });
			},
			/**
			 * 生成订单号
			 */
			postDemand() {
				return new Promise(resolve => {
					const demand_type_id = this.demands[this.currentDemandIndex].demand_type_id
					postDemand({
						demand_type_id: this.demands[this.currentDemandIndex].demand_type_id,
						shipping_address_id: this.address.shipping_address_id,
						describe: this.describe,
						discount_coupon_id: this.couponsIndex > -1 ? this.filterCoupons[this.couponsIndex].discount_coupon_id : '',
						print_order_id: demand_type_id === 1 ? this.selectedOrder.print_order_id : '',
						express_addressee_name: demand_type_id === 3 ? this.address.name : '',
						courier_services_company_id: demand_type_id === 3 ? this.expressCompanys[this.currentCompanyIndex].courier_services_company_id : '',
						delivery_time: demand_type_id === 3 ? this.periods[this.currentPeriodsIndex] : '',
						payment_type: this.paymentMethods[this.paymentMethodIndex].value,
						express_message: demand_type_id === 3 ? this.express_message : ''
					}).then(res => {
						this.order_result = res.result
						resolve(res.result )
					})
				})
			},
			/**
			 * 判断支付方式 采取不同方法
			 * @param {Object} 订单编号
			 */
			payType(res) {
				//余额支付
				if (this.paymentMethods[this.paymentMethodIndex].value === 1) {
					//验证密码
					this.payFlag = true;
					this.paymentModalTitle = this.userInfo.is_set_payment_code === 0 ? '设置安全密码' : '校验安全密码';
				}
				//微信支付
				else {
					//判断是否零元
					if(res.is_actual_price_zero) {
						uni.redirectTo({
							url: `/community-pages/reward?order_number=${res.order_number}&order_id=${res.demand_order_id}`
						});
					}else {
						//第二步：获取支付参数
						this.paymentInterfaceEvent().then(result => {
							//第三步：发起微信支付
							this.payEvent(result);
						});
					}
				}
			},
			/**
			 *  获取支付流水号
			 */
			paymentInterfaceEvent(password) {
				return new Promise(resolve => {
					const order_result = this.order_result
					paymentInterface({
						payType: this.paymentMethods[this.paymentMethodIndex].value,
						body: this.demands[this.currentDemandIndex].demand_type_name,
						out_trade_no: order_result.order_number || '',
						order_id: order_result.demand_order_id || '',
						payment_code: password || '',
						orderType: 2
					}).then(res => {
						resolve(res.result);
					});
				});
			},
			/**
			 * 支付
			 * @param result
			 * @param item
			 */
			payEvent(result) {
				const { nonceStr, paySign, signType, timeStamp } = result;
				wx.requestPayment({
					nonceStr: nonceStr,
					package: result.package,
					paySign: paySign,
					signType: signType,
					timeStamp: timeStamp.toString(),
					success: res => {
						const order_result = this.order_result
						if (res.errMsg === 'requestPayment:ok') {
							uni.redirectTo({
								url: `/community-pages/reward?order_number=${order_result.order_number}&order_id=${order_result.demand_order_id}`
							});
						}
					},
					fail: res => {
						if (res.errMsg !== 'requestPayment:fail cancel') {
							wx.showModal({
								title: '支付错误',
								content: '可能遇到网络堵塞，建议重新尝试提交预约'
							});
						}
						wx.redirectTo({
							url: '/user-pages/released-order'
						});
					}
				});
			},
			/**
			 * 输入密码后确认事件
			 * @param {Object} value 密码
			 */
			confirmPassword(value) {
				if (this.userInfo.is_set_payment_code === 0) {
					//调接口
					changePaymentCode({
						payment_code: value
					}).then(res=> {
						this.userInfo.is_set_payment_code = 1;
						this.$refs.PaymentModal.hideModal();
						clearTimeout(this.timer);
						this.timer = setTimeout(() => {
							this.payFlag = true;
							this.paymentModalTitle = this.userInfo.is_set_payment_code === 0 ? '设置安全密码' : '校验安全密码';
						}, 1000);
					}).catch(err => {
						this.$refs.PaymentModal.clear()
					})
				} else {
					//第二步：获取支付参数
					this.paymentInterfaceEvent(value).then(res => {
						uni.redirectTo({
							url: `/community-pages/reward?order_number=${this.order_result.order_number}&order_id=${this.order_result.demand_order_id}`
						});
					});
					this.$refs.PaymentModal.hideModal();
				}
			},
		}
    }
</script>

<style lang="scss">
.publish-wrap {
	float: right;
	width: 90%;
	margin-bottom: 20px;

	.card {
		border-radius: $uni-border-radius-base 0 0 $uni-border-radius-base !important;
		margin-bottom: 12px;

		.cu-form-group {
			padding: 0;
			min-height: 60rpx;
			color: $uni-text-color;

			+.cu-form-group {
				border-top: none;
			}

			.title-wrap {}

			input {
				text-align: right;
				font-size: 28rpx;
				padding-right: 0;
			}

			.input-placeholder {
				color: #aaaaaa
			}

			picker {
				padding-right: 30rpx;

				&::after {
					font-size: 28rpx;
					color: #aaaaaa;
					width: 70rpx;
					line-height: 60rpx;
				}

			}

			.picker {
				line-height: 60rpx;

			}
		}
	}

	.form-btn {
		border-radius: $uni-border-radius-base 0 0 $uni-border-radius-base !important;
		box-shadow: $uni-box-shadow;
	}

	textarea {
		width: 100%;
		height: 50px;
	}

}
.cu-dialog.print-dialog {
	height: 60%;
	overflow-y: scroll;

	.cu-bar {
		position: fixed;
		top: 40%;
		right: 0;
		left: 0;
		z-index: 9;

	}

	.list-wrap {
		margin-top: 100rpx;
		.text-cut {
			width: 500rpx;
			display: block !important;
			text-align: left;

		}
	}
}
</style>
